package top.shiyiri.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author Aunean
 * @date 2022/1/30 17:06
 */
public class UploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("文件上传成功");
//        ServletInputStream inputStream = req.getInputStream();
//
//        byte[] buffer = new byte[1024];
//        int read = inputStream.read(buffer);
//        System.out.println(new String(buffer, 0, read));

        //1.判断上传的数据是否是多段数据（只有是多段的数据，才是文件上传的）
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory工厂实现类
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

            try {
                //解析上传的数据，得到每一个扁担想FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //循环判断每一个表单项，是普通类型还是上传的文件
                for (FileItem item : list) {
                    if (item.isFormField()) {
                        //普通表单项
                        System.out.println("表单项的name属性值：" + item.getFieldName());
                        //参数UTF-8解决乱码问题
                        System.out.println("表单项的value属性值：" + item.getString("UTF-8"));
                    } else {
                        //上传的文件
                        System.out.println("表单项的name属性值：" + item.getFieldName());
                        System.out.println("上传的文件名：" + item.getName());
                        //写入文件
                        item.write(new File("D:/photo/" + item.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
